//
//  BlurView.swift
//  Counter
//
//  Created by huangguojian on 2021/11/26.
//

import SwiftUI

///模糊背景
struct BlurView: UIViewRepresentable {
    typealias UIViewType = UIVisualEffectView
    
    let style: UIBlurEffect.Style
    
    init(style: UIBlurEffect.Style) {
        self.style = style
        print("Init")
    }
    
    func makeUIView(context: Context) -> UIVisualEffectView {
        print("makeUIView")
        let blurView = UIVisualEffectView()
        blurView.translatesAutoresizingMaskIntoConstraints = false
        return blurView
    }
    
    func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
        print("Update")
        uiView.effect = UIBlurEffect(style: self.style)
    }
}

extension View {
    
    /// 半透明模糊背景
    /// - Parameter style: 模糊类型
    /// - Returns: some View
    func blurBackground(style: UIBlurEffect.Style) -> some View {
        ZStack {
            BlurView(style: style)
            self
        }
    }
}

struct NormalView: View {
    
    @State var blurStyle: UIBlurEffect.Style
    
    var body: some View {
        HStack {
            Text("Hello World")
                .padding()
                .background(.green)
                .cornerRadius(8)
        }
        .padding()
        .blurBackground(style: blurStyle)
        .cornerRadius(8)
    }
}

struct BlurViewPreviews: PreviewProvider {
    static var previews: some View {
        
        VStack(spacing: 8) {
            NormalView(blurStyle: .light)
            NormalView(blurStyle: .dark)
        }
        .fixedSize()
        .frame(maxWidth: .greatestFiniteMagnitude, maxHeight: .greatestFiniteMagnitude)
        .background(.blue)
        
    }
}
